<template>
  <PageWrapper :title="t('office.word.title')">
    <template #headerContent>
      <div class="flex justify-between items-center">
        <span class="flex-1">
          {{ t('office.word.description') }}
        </span>
      </div>
    </template>
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1">
        <template #tab>
          <span>
            <FileWordOutlined />
            {{ t('office.word.templateGenerate') }}
          </span>
        </template>
        <div>
          <a-card ref="tipsRef" :title="t('office.word.templateSyntax')">
            <a-typography-title :level="3">变量</a-typography-title>
            <a-typography-title :level="5">
              模板语法使用的是jinja2语法，参考文档：
              <a
                href="https://docs.jinkan.org/docs/jinja2/templates.html#variables"
                target="_blank"
              >
                https://docs.jinkan.org/docs/jinja2/templates.html#variables
              </a>
            </a-typography-title>
            <a-space direction="vertical">
              <a-typography-text type="danger">注意：变量名不支持中文</a-typography-text>
              <a-space direction="horizontal">
                <template #split>
                  <a-divider type="vertical" />
                </template>
                <a-typography-link @click="downloadTemplate('template')">
                  模板示例
                </a-typography-link>
                <a-typography-link @click="downloadTemplate('data')">
                  模板数据示例
                </a-typography-link>
              </a-space>
            </a-space>
          </a-card>
          <a-divider />
          <a-card :title="t('office.word.upload')" :bordered="false" ref="uploadRef">
            <a-upload-dragger
              v-model:fileList="templateFile"
              name="file"
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              @change="uploadChange"
              :before-upload="templateBeforeUpload"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined />
              </p>
              <p class="ant-upload-text">{{ t('office.word.uploadTips') }}</p>
              <p class="ant-upload-text">{{ t('office.word.wordType') }}</p>
            </a-upload-dragger>
          </a-card>
          <a-divider />
          <a-card :title="t('office.word.input')" :bordered="false" ref="inputRef">
            <a-upload-dragger
              v-model:fileList="dataFile"
              name="file"
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              :before-upload="templateDataBeforeUpload"
              @change="uploadChange"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined />
              </p>
              <p class="ant-upload-text">{{ t('office.word.uploadTips') }}</p>
              <p class="ant-upload-text">{{ t('office.word.excelType') }}</p>
            </a-upload-dragger>
          </a-card>
          <a-divider />
          <a-row justify="center">
            <a-col :span="2">
              <a-button ref="generateRef" type="primary">
                <CheckCircleOutlined />{{ t('office.word.generate') }}
              </a-button>
            </a-col>
            <a-col :span="18">
              <a-progress
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                :percent="genProgress"
                ref="progressRef"
              />
            </a-col>
            <a-col :span="2" :offset="1">
              <a-button ref="downloadRef" type="primary" :disabled="100 != genProgress">
                <CloudDownloadOutlined />{{ t('office.word.download') }}
              </a-button>
            </a-col>
          </a-row>
          <a-tour :open="tourOpen" type="primary" :steps="steps" @close="handleTour(false)" />
        </div>
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { PageWrapper } from '@/components/Page';
  import { isWord, isExcel } from '@/utils/file/type';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { ref } from 'vue';
  import {
    FileWordOutlined,
    CloudDownloadOutlined,
    InboxOutlined,
    CheckCircleOutlined,
  } from '@ant-design/icons-vue';
  import {
    Tabs,
    Tour,
    UploadDragger,
    message,
    Card,
    Divider,
    TypographyTitle,
    TypographyText,
    TypographyLink,
    Space,
    Progress,
    Row,
    Col,
  } from 'ant-design-vue';
  import type { TourProps, UploadChangeParam } from 'ant-design-vue';
  import { downloadByUrl } from '@/utils/file/download';

  const ATabs = Tabs;
  const ATabPane = Tabs.TabPane;
  const ATour = Tour;
  const AUploadDragger = UploadDragger;
  const ACard = Card;
  const ADivider = Divider;
  const ATypographyTitle = TypographyTitle;
  const ATypographyText = TypographyText;
  const ATypographyLink = TypographyLink;
  const ASpace = Space;
  const AProgress = Progress;
  const ARow = Row;
  const ACol = Col;

  // 当前激活的标签页索引
  const activeKey = ref('1');

  // 文档生成进度
  let genProgress = ref(0);

  const { t } = useI18n();

  // 引导对象
  const tipsRef = ref(null);
  const uploadRef = ref(null);
  const inputRef = ref(null);
  const downloadRef = ref(null);
  const generateRef = ref(null);
  const progressRef = ref(null);
  // 是否开启引导
  const tourOpen = ref<boolean>(true);

  const steps: TourProps['steps'] = [
    {
      title: 'Tips',
      description: t('office.word.tipsDesc'),
      placement: 'bottom',
      target: () => tipsRef.value && tipsRef.value.$el,
    },
    {
      title: 'Upload File',
      description: t('office.word.uploadDesc'),
      placement: 'bottom',
      target: () => uploadRef.value && uploadRef.value.$el,
    },
    {
      title: 'Input Fill',
      description: t('office.word.inputDesc'),
      placement: 'bottom',
      target: () => inputRef.value && inputRef.value.$el,
    },
    {
      title: 'Generate',
      description: t('office.word.generateDesc'),
      placement: 'top',
      target: () => generateRef.value && generateRef.value.$el,
    },
    {
      title: 'Progress',
      description: t('office.word.progressDesc'),
      placement: 'top',
      target: () => progressRef.value && progressRef.value.$el,
    },
    {
      title: 'Download',
      description: t('office.word.downloadDesc'),
      placement: 'top',
      target: () => downloadRef.value && downloadRef.value.$el,
    },
  ];

  const handleTour = (val: boolean): void => {
    tourOpen.value = val;
  };

  // 模板文件
  const templateFile = ref([]);
  // 模板数据文件
  const dataFile = ref([]);
  // 文件上传变化
  const uploadChange = (info: UploadChangeParam) => {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  };

  // 模板文件上传前校验
  const templateBeforeUpload: UploadProps['beforeUpload'] = (file) => {
    const check = isWord(file.type);
    if (!check) {
      message.error(`${file.name} is not a docx file`);
    }
    return check || Upload.LIST_IGNORE;
  };

  // 模板数据文件上传前校验
  const templateDataBeforeUpload: UploadProps['beforeUpload'] = (file) => {
    const check = isExcel(file.type);
    if (!check) {
      message.error(`${file.name} is not a docx file`);
    }
    return check || Upload.LIST_IGNORE;
  };

  // 下载模板数据
  const downloadTemplate = (flag: string) => {
    const domain = window.location.host;
    const protocol = window.location.protocol;
    const baseUrl = protocol + '//' + domain;
    let url = baseUrl + '/src/assets/template/docx/template.docx';
    if ('data' == flag) {
      url = baseUrl + '/src/assets/template/docx/data.xlsx';
    }
    downloadByUrl({
      url,
      target: '_self',
    });
  };
</script>
